package indi.lddsdu.index;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;
import indi.lddsdu.bean.Record;
import indi.lddsdu.exception.RecordException;
import indi.lddsdu.util.DButil;

/**
 * 用来创建索引，目前阶段的索引字段只有content，对于title没有创建
 * 从数据库中读取索引后创建，最后看情况在servlet中实现对于title，content同时的索引
 * Created by jack on 18/6/10.
 */
public class IndexCreate {
    //存储索引的目录
    public final String INDEX_DIR;
    private final int INTERVAL = 500;
    private int startIndex = 0;

    private Analyzer analyzer;
    private Directory directory;
    private IndexWriter indexWriter;

    /**
     * 构造函数，用来初始化一些基本的变量
     */
    public IndexCreate(String index_dir) throws IOException {
        INDEX_DIR = index_dir;
        analyzer = new IKAnalyzer();
        directory = FSDirectory.open(Paths.get(index_dir));
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        indexWriter = new IndexWriter(directory, config);
    }

    /**
     * 创建索引
     */
    public void createIndex() throws SQLException, RecordException, IOException {
        while (true) {
            List<Record> recordList = DButil.listRecords(startIndex, INTERVAL);
            startIndex += INTERVAL;
            if(recordList.size() == 0){
                //查询不出数据了
                break;
            }
            for(Record record : recordList){
                if (record.isText()) {
                    createIndex(record);
                }else{
                    System.out.println(String.format("%s is not a txt file", record.getFilePath()));
                }
            }
        }
        closeWriter();
    }


    /**
     *根据单个传入的Record来创建索引
     *这里只管调用lucene的方法来设置对应的数据即可
     */
    public void createIndex(Record record) throws IOException {

        Document document = new Document();

        Field titleField = new TextField("title", record.getTitle(), Field.Store.YES);
//        titleField.setBoost(100f);
        document.add(titleField);

        System.out.println("create index for file " + record.getFilePath());
        document.add(new TextField("content", txt2String(record.getFilePath()), Field.Store.YES));
        document.add(new TextField("link", record.getUrl(), Field.Store.YES));

        indexWriter.addDocument(document);
        indexWriter.commit();
    }

    /**
     * 关闭indexWriter
     * @throws IOException
     */
    private void closeWriter() throws IOException {
        if (indexWriter != null){
            indexWriter.close();
        }
    }


    /**
     * 读取txt文件内容
     * @param filePath  txt文件的路径
     * @return
     */
    public String txt2String(String filePath){
        return txt2String(new File(filePath));
    }

    /**
     * 读取txt文件内容
     * @param file  txt file对象
     * @return
     */
    public static String txt2String(File file){
        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result = result + "\n" +s;
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }



}
